<template>
  <div class="user-form-component">
    <!-- 表单内容 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="user-form"
    >
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- 左侧主要信息 -->
        <div class="space-y-6">
          <!-- 基本信息 -->
          <el-card shadow="never" class="form-card">
            <template #header>
              <h3 class="text-lg font-semibold">基本信息</h3>
            </template>
            
            <!-- 编辑模式下显示用户ID -->
            <el-form-item v-if="mode === 'edit'" label="用户ID">
              <el-input v-model="formData.id" disabled />
            </el-form-item>

            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="formData.username"
                placeholder="请输入用户名"
                maxlength="50"
                show-word-limit
                :disabled="mode === 'edit'"
              />
            </el-form-item>

            <el-form-item label="昵称" prop="nickname">
              <el-input
                v-model="formData.nickname"
                placeholder="请输入用户昵称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="formData.email"
                placeholder="请输入邮箱地址"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="密码" prop="passwordHash" v-if="mode === 'add'">
              <el-input
                v-model="formData.passwordHash"
                type="password"
                placeholder="请输入密码"
                maxlength="255"
                show-password
              />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword" v-if="mode === 'add'">
              <el-input
                v-model="formData.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                maxlength="255"
                show-password
              />
            </el-form-item>
          </el-card>

          <!-- 头像上传 -->
          <el-card shadow="never" class="form-card">
            <template #header>
              <h3 class="text-lg font-semibold">头像设置</h3>
            </template>
            
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                action="#"
                :http-request="handleAvatarUpload"
              >
                <img v-if="formData.avatarUrl" :src="formData.avatarUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="text-sm text-gray-500 mt-2">
                支持 JPG、PNG 格式，文件大小不超过 2MB
              </div>
            </el-form-item>
          </el-card>
        </div>

        <!-- 右侧权限信息 -->
        <div class="space-y-6">
          <el-card shadow="never" class="form-card">
            <template #header>
              <h3 class="text-lg font-semibold">权限信息</h3>
            </template>
            
            <el-form-item label="用户角色" prop="role">
              <el-select
                v-model="formData.role"
                placeholder="请选择用户角色"
                class="w-full"
              >
                <el-option label="管理员" value="admin" />
                <el-option label="普通用户" value="user" />
              </el-select>
            </el-form-item>

            <el-form-item label="用户状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="备注">
              <el-input
                v-model="formData.remark"
                type="textarea"
                placeholder="请输入备注信息"
                :rows="3"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-card>

          <!-- 编辑模式下显示元数据 -->
          <el-card v-if="mode === 'edit'" shadow="never" class="form-card">
            <template #header>
              <h3 class="text-lg font-semibold">元数据</h3>
            </template>
            
            <el-form-item label="创建时间">
              <el-input v-model="formData.createdAt" disabled />
            </el-form-item>
            
            <el-form-item label="最后登录">
              <el-input v-model="formData.lastLoginTime" disabled />
            </el-form-item>

            <el-form-item label="登录次数">
              <el-input v-model="formData.loginCount" disabled />
            </el-form-item>
            
            <el-form-item label="最后更新">
              <el-input v-model="formData.updatedAt" disabled />
            </el-form-item>
          </el-card>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 定义组件属性
const props = defineProps({
  mode: {
    type: String,
    required: true,
    validator: (value) => ['add', 'edit'].includes(value)
  },
  userId: {
    type: [String, Number],
    default: null
  },
  initialData: {
    type: Object,
    default: () => ({})
  }
})

// 定义事件
const emit = defineEmits(['save', 'delete', 'cancel'])

// 组件内部状态
const formRef = ref()
const saving = ref(false)

// 表单数据
const formData = reactive({
  id: '',
  username: '',
  email: '',
  passwordHash: '',
  confirmPassword: '',
  nickname: '',
  avatarUrl: '',
  role: 'user',
  status: 1,
  lastLoginTime: '',
  loginCount: 0,
  createdAt: '',
  updatedAt: '',
  remark: ''
})

// 表单验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (formData.confirmPassword !== '') {
      formRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== formData.passwordHash) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度应在3-50个字符之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  passwordHash: [
    { required: true, message: '请输入密码', trigger: 'blur', validator: validatePass },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur', validator: validatePass2 }
  ],
  role: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ]
}

// 计算属性
const currentTime = computed(() => {
  return new Date().toISOString().slice(0, 19).replace('T', ' ')
})

// 初始化表单数据
const initFormData = () => {
  if (props.mode === 'add') {
    // 新增模式：设置默认值
    Object.assign(formData, {
      id: '',
      username: '',
      email: '',
      passwordHash: '',
      confirmPassword: '',
      nickname: '',
      avatarUrl: '',
      role: 'user',
      status: 1,
      lastLoginTime: '',
      loginCount: 0,
      createdAt: '',
      updatedAt: '',
      remark: ''
    })
  } else if (props.mode === 'edit' && props.initialData) {
    // 编辑模式：使用传入的初始数据
    Object.assign(formData, {
      id: props.initialData.id || '',
      username: props.initialData.username || '',
      email: props.initialData.email || '',
      passwordHash: '',
      confirmPassword: '',
      nickname: props.initialData.nickname || '',
      avatarUrl: props.initialData.avatarUrl || '',
      role: props.initialData.role || 'user',
      status: props.initialData.status || 1,
      lastLoginTime: props.initialData.lastLoginTime || '',
      loginCount: props.initialData.loginCount || 0,
      createdAt: props.initialData.createdAt || '',
      updatedAt: props.initialData.updatedAt || '',
      remark: props.initialData.remark || ''
    })
  }
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功
const handleAvatarSuccess = (response, file) => {
  formData.avatarUrl = URL.createObjectURL(file.raw)
}

// 头像上传处理
const handleAvatarUpload = (options) => {
  // 这里应该调用实际的文件上传API
  // 暂时使用本地URL
  const file = options.file
  if (beforeAvatarUpload(file)) {
    formData.avatarUrl = URL.createObjectURL(file)
    options.onSuccess()
  } else {
    options.onError()
  }
}

// 保存用户
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    saving.value = true
    
    // 触发保存事件，让父组件处理
    emit('save', { ...formData })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saving.value = false
  }
}

// 删除用户
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户「${formData.username}」吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 触发删除事件，让父组件处理
    emit('delete', formData.id)
  } catch {
    // 用户取消删除
  }
}

// 监听初始数据变化
watch(() => props.initialData, () => {
  if (props.mode === 'edit') {
    initFormData()
  }
}, { deep: true })

// 暴露方法给父组件
defineExpose({
  formRef,
  formData,
  validate: () => formRef.value?.validate(),
  resetFields: () => formRef.value?.resetFields(),
  handleSave,
  handleDelete,
  saving
})

// 组件初始化
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.user-form-component {
  @apply w-full;
}

.form-card {
  @apply border border-gray-200 ;
}

.form-card :deep(.el-card__header) {
  @apply bg-gray-50  border-b border-gray-200 ;
}

.user-form :deep(.el-form-item__label) {
  @apply text-gray-700  font-medium;
}

.avatar-uploader {
  @apply text-center;
}

.avatar-uploader .el-upload {
  @apply border border-dashed border-gray-300  rounded-lg cursor-pointer relative overflow-hidden transition-colors hover:border-blue-500;
}

.avatar-uploader .el-upload:hover {
  @apply border-blue-500;
}

.avatar-uploader-icon {
  @apply text-3xl text-gray-400 w-24 h-24 leading-none;
}

.avatar {
  @apply w-24 h-24 block;
}
</style>
